'use strict';

const { HttpException } = require('../core/httpException');
// const { isDev } = require('../core/env');
const isDev = true;
/**
 * @param {*} ctx
 * @param {*} next
 * HTTP Status Code 2xx, 4xx, 5xx
 * message
 * error_code
 * request_url
 */

module.exports = () => {
  return async (ctx, next) => {
    try {
      await next();
    } catch (error) {

      // 开发环境 or 生产环境
      const isHttpException = error instanceof HttpException;
      // 不是生产环境并且不是HttpException类型，抛出异常
      if (isDev && !isHttpException) {
        throw error;
      }

      // 已知异常
      if (isHttpException) {
        const body = {
          returnMessage: error.returnMessage,
          returnCode: error.returnCode,
          request: `${ctx.method} ${ctx.path}`,
          bean: error.bean,
          beans: error.beans,
        };
        ctx.body = body;
        ctx.status = error.code;
      } else { // 未知异常
        const body = {
          returnMessage: 'we made a mistake',
          returnCode: '9999',
          request: `${ctx.method} ${ctx.path}`,
        };
        ctx.body = body;
        ctx.status = 500;
      }
    }
  };
};

